<template>
  <div class="print-template-designer">
    <el-dialog
      v-model="visible"
      title="打印模板设计器"
      width="90%"
      height="90%"
      :before-close="handleClose"
      custom-class="sv-print-dialog"
    >
      <!-- 顶部工具栏 -->
      <div class="sv-top-toolbar">
        <div class="toolbar-section">
          <el-button-group>
            <el-button icon="el-icon-plus" @click="newTemplate">新建</el-button>
            <el-button icon="el-icon-folder-opened" @click="openTemplate">打开</el-button>
            <el-button icon="el-icon-save" @click="saveTemplate">保存</el-button>
            <el-button icon="el-icon-upload" @click="exportTemplate">导出</el-button>
            <el-button icon="el-icon-download" @click="importTemplate">导入</el-button>
          </el-button-group>
        </div>
        <div class="toolbar-section">
          <el-button-group>
            <el-button icon="el-icon-back" @click="undo">撤销</el-button>
            <el-button icon="el-icon-refresh" @click="redo">重做</el-button>
            <el-button icon="el-icon-delete" @click="deleteSelected">删除</el-button>
          </el-button-group>
        </div>
        <div class="toolbar-section">
          <el-button-group>
            <el-button icon="el-icon-zoom-in" @click="zoomIn">放大</el-button>
            <el-input-number v-model="zoomLevel" :min="50" :max="200" @change="onZoomChange" />
            <span>%</span>
            <el-button icon="el-icon-zoom-out" @click="zoomOut">缩小</el-button>
            <el-button @click="fitToPage">适应页面</el-button>
          </el-button-group>
        </div>
        <div class="toolbar-section">
          <el-button-group>
            <el-button type="primary" @click="previewPrint">预览</el-button>
            <el-button type="success" @click="printDirectly">打印</el-button>
            <el-button type="warning" @click="printSettings">设置</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 主设计区域 -->
      <div class="sv-main-container">
        <!-- 左侧组件列表 -->
        <div class="sv-left-panel">
          <div class="panel-header">组件库</div>
          <div class="panel-content">
            <div class="component-category">
              <div class="category-title">基础组件</div>
              <div class="component-list">
                <div class="component-item" @click="addTextComponent">
                  <span class="component-icon">📝</span>
                  <span>文本</span>
                </div>
                <div class="component-item" @click="addImageComponent">
                  <span class="component-icon">🖼️</span>
                  <span>图片</span>
                </div>
                <div class="component-item" @click="addTableComponent">
                  <span class="component-icon">📊</span>
                  <span>表格</span>
                </div>
                <div class="component-item" @click="addLineComponent">
                  <span class="component-icon">📏</span>
                  <span>线条</span>
                </div>
                <div class="component-item" @click="addRectangleComponent">
                  <span class="component-icon">⬜</span>
                  <span>矩形</span>
                </div>
              </div>
            </div>
            <div class="component-category">
              <div class="category-title">数据组件</div>
              <div class="component-list">
                <div class="component-item" @click="addPatientInfo">
                  <span class="component-icon">👤</span>
                  <span>患者信息</span>
                </div>
                <div class="component-item" @click="addBloodPressure">
                  <span class="component-icon">❤️</span>
                  <span>血压信息</span>
                </div>
                <div class="component-item" @click="addBloodGlucose">
                  <span class="component-icon">🩸</span>
                  <span>血糖信息</span>
                </div>
                <div class="component-item" @click="addChart">
                  <span class="component-icon">📈</span>
                  <span>图表</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 中间设计画布 - 显示报告详情 -->
        <div class="sv-center-canvas">
          <div class="canvas-header">
            <div class="page-info">
              <span>页面: 1/1</span>
              <span>大小: {{ paperSize }}</span>
            </div>
          </div>
          <div class="canvas-container" :style="{ transform: `scale(${zoomLevel / 100})` }">
            <div class="designer-area" ref="designerRef">
              <!-- 报告详情内容 - 直接从HealthReportView.vue复制并适配 -->
              <div class="health-report-content">
                <!-- 报告头部信息 -->
                <div class="report-header">
                  <h3 class="report-title">综合健康报告</h3>
                  <div class="report-date">编制日期：{{ props.reportData?.reportDate || formatCurrentDate() }}</div>
                </div>

                <!-- 患者基本信息 -->
                <div class="report-section">
                  <h4 class="section-title">基本信息</h4>
                  <div class="patient-info">
                    <div class="info-item"><span class="info-label">姓名：</span><span class="info-value">{{ props.reportData?.patientInfo?.name || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">年龄：</span><span class="info-value">{{ props.reportData?.patientInfo?.age || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">性别：</span><span class="info-value">{{ props.reportData?.patientInfo?.gender || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">身份证号：</span><span class="info-value">{{ props.reportData?.patientInfo?.patientId || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">身高：</span><span class="info-value">{{ props.reportData?.patientInfo?.height || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">体重：</span><span class="info-value">{{ props.reportData?.patientInfo?.weight || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">BMI：</span><span class="info-value">{{ props.reportData?.patientInfo?.bmi || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">血型：</span><span class="info-value">{{ props.reportData?.patientInfo?.bloodType || '-' }}</span></div>
                    <div class="info-item"><span class="info-label">职业：</span><span class="info-value">{{ props.reportData?.patientInfo?.occupation || '-' }}</span></div>
                  </div>
                </div>

                <!-- 血压信息 -->
                <div class="report-section">
                  <h4 class="section-title">血压</h4>
                  <div class="blood-pressure-chart">
                    <div class="pressure-info">
                      <div class="pressure-main">
                        <span class="pressure-value systolic">{{ props.reportData?.bloodPressure?.systolic || '-' }}</span>
                        <span class="pressure-unit">mmHg</span>
                        <span class="pressure-separator">/</span>
                        <span class="pressure-value diastolic">{{ props.reportData?.bloodPressure?.diastolic || '-' }}</span>
                        <span class="pressure-unit">mmHg</span>
                      </div>
                      <div class="pressure-evaluation">{{ props.reportData?.bloodPressure?.evaluation || '-' }}</div>
                      <div class="pressure-time">{{ props.reportData?.bloodPressure?.recordTime || '-' }}</div>
                    </div>
                    <div class="chart-container">
                      <div class="blood-pressure-bar">
                        <div class="bar-item danger" style="height: 80px;"></div>
                        <div class="bar-item warning" style="height: 60px;"></div>
                        <div class="bar-item normal" style="height: 40px;"></div>
                        <div class="bar-item low" style="height: 20px;"></div>
                      </div>
                      <div class="chart-labels">
                        <div>危险血压</div>
                        <div>轻度高血压</div>
                        <div>正常血压</div>
                        <div>低血压</div>
                      </div>
                    </div>
                  </div>
                  <div class="indicator-score">
                    <div class="score-item">
                      <span>收缩压评分</span>
                      <span class="score-number">75</span>
                    </div>
                    <div class="score-item">
                      <span>舒张压评分</span>
                      <span class="score-number">80</span>
                    </div>
                    <div class="score-item">
                      <span>心率评分</span>
                      <span class="score-number">85</span>
                    </div>
                    <div class="score-item">
                      <span>心血管健康</span>
                      <span class="score-number">82</span>
                    </div>
                  </div>
                </div>

                <!-- 血糖信息 -->
                <div class="report-section">
                  <h4 class="section-title">血糖</h4>
                  <div class="glucose-info">
                    <div class="glucose-item">
                      <div class="glucose-label">空腹血糖</div>
                      <div class="glucose-value">{{ props.reportData?.bloodGlucose?.fasting || '-' }} mmol/L</div>
                    </div>
                    <div class="glucose-item">
                      <div class="glucose-label">餐后2小时血糖</div>
                      <div class="glucose-value">{{ props.reportData?.bloodGlucose?.twoHoursAfterMeal || '-' }} mmol/L</div>
                    </div>
                    <div class="glucose-item">
                      <div class="glucose-label">糖化血红蛋白</div>
                      <div class="glucose-value">{{ props.reportData?.bloodGlucose?.glycatedHemoglobin || '-' }} %</div>
                    </div>
                    <div class="glucose-evaluation">
                      <div class="evaluation-label">评估：</div>
                      <div class="evaluation-value">{{ props.reportData?.bloodGlucose?.evaluation || '-' }}</div>
                    </div>
                    <div class="glucose-time">{{ props.reportData?.bloodGlucose?.recordTime || '-' }}</div>
                  </div>
                  <div class="glucose-chart">
                    <div class="chart-row">
                      <div class="chart-bar low" style="width: 40%;"></div>
                      <div class="chart-bar normal" style="width: 30%;"></div>
                      <div class="chart-bar high" style="width: 30%;"></div>
                    </div>
                    <div class="chart-legend">
                      <span>低血糖</span>
                      <span>正常</span>
                      <span>高血糖</span>
                    </div>
                  </div>
                  <div class="indicator-score">
                    <div class="score-item">
                      <span>空腹血糖评分</span>
                      <span class="score-number">72</span>
                    </div>
                    <div class="score-item">
                      <span>餐后血糖评分</span>
                      <span class="score-number">65</span>
                    </div>
                    <div class="score-item">
                      <span>糖化血红蛋白评分</span>
                      <span class="score-number">70</span>
                    </div>
                    <div class="score-item">
                      <span>血糖控制</span>
                      <span class="score-number">69</span>
                    </div>
                  </div>
                </div>

                <!-- 生化指标 -->
                <div class="report-section">
                  <h4 class="section-title">生化指标</h4>
                  <div class="biochemical-table">
                    <table>
                      <thead>
                        <tr>
                          <th>检测项目</th>
                          <th>总胆固醇</th>
                          <th>甘油三酯</th>
                          <th>HDL-C</th>
                          <th>LDL-C</th>
                          <th>尿酸</th>
                          <th>尿素氮</th>
                          <th>肌酐</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td>检测值</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.totalCholesterol || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.triglycerides || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.hdlCholesterol || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.ldlCholesterol || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.uricAcid || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.bloodUreaNitrogen || '-' }}</td>
                          <td>{{ props.reportData?.biochemicalIndicators?.serumCreatinine || '-' }}</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                <!-- 用药记录 -->
                <div class="report-section">
                  <h4 class="section-title">用药记录</h4>
                  <div class="medication-table">
                    <table>
                      <thead>
                        <tr>
                          <th>序号</th>
                          <th>药品名称</th>
                          <th>剂量</th>
                          <th>频次</th>
                          <th>用药时间</th>
                          <th>用药时长</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(med, index) in props.reportData?.medicationRecords || []" :key="index">
                          <td>{{ index + 1 }}</td>
                          <td>{{ med.medicationName }}</td>
                          <td>{{ med.dose }}</td>
                          <td>{{ med.frequency }}</td>
                          <td>{{ med.administrationTime }}</td>
                          <td>{{ med.duration }}</td>
                        </tr>
                        <tr v-if="!props.reportData?.medicationRecords || props.reportData.medicationRecords.length === 0">
                          <td colspan="6" style="text-align: center;">暂无用药记录</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>

                <!-- 运动评估 -->
                <div class="report-section">
                  <h4 class="section-title">运动评估</h4>
                  <div class="exercise-info">
                    <div class="exercise-stats">
                      <div class="stat-item">
                        <div class="stat-label">每周运动次数</div>
                        <div class="stat-value">{{ props.reportData?.exerciseAssessment?.weeklyExerciseFrequency || '-' }}</div>
                      </div>
                      <div class="stat-item">
                        <div class="stat-label">平均运动时长</div>
                        <div class="stat-value">{{ props.reportData?.exerciseAssessment?.averageExerciseDuration || '-' }}</div>
                      </div>
                      <div class="stat-item">
                        <div class="stat-label">运动强度</div>
                        <div class="stat-value">{{ props.reportData?.exerciseAssessment?.exerciseIntensity || '-' }}</div>
                      </div>
                      <div class="stat-item">
                        <div class="stat-label">运动类型</div>
                        <div class="stat-value">{{ (props.reportData?.exerciseAssessment?.exerciseTypes || []).join('、') || '-' }}</div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 综合评分 -->
                <div class="report-section">
                  <h4 class="section-title">综合评分</h4>
                  <div class="overall-score">
                    <div class="score-display">
                      <div class="score-number-large">75</div>
                      <div class="score-level">良好</div>
                    </div>
                    <div class="score-breakdown">
                      <div class="score-item">
                        <span>心血管健康</span>
                        <span class="score-number">82</span>
                      </div>
                      <div class="score-item">
                        <span>代谢指标</span>
                        <span class="score-number">70</span>
                      </div>
                      <div class="score-item">
                        <span>生活方式</span>
                        <span class="score-number">78</span>
                      </div>
                      <div class="score-item">
                        <span>用药依从性</span>
                        <span class="score-number">85</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="canvas-footer">
            <div class="ruler-horizontal"></div>
          </div>
        </div>

        <!-- 右侧属性面板 -->
        <div class="sv-right-panel">
          <div class="panel-header">属性设置</div>
          <div class="panel-content">
            <div v-if="selectedElement" class="property-section">
              <div class="property-title">{{ selectedElement.type }} 属性</div>
              <div class="property-item">
                <label>位置 X:</label>
                <el-input-number v-model="selectedElement.x" :min="0" @change="updateSelectedElement" />
              </div>
              <div class="property-item">
                <label>位置 Y:</label>
                <el-input-number v-model="selectedElement.y" :min="0" @change="updateSelectedElement" />
              </div>
              <div class="property-item">
                <label>宽度:</label>
                <el-input-number v-model="selectedElement.width" :min="10" @change="updateSelectedElement" />
              </div>
              <div class="property-item">
                <label>高度:</label>
                <el-input-number v-model="selectedElement.height" :min="10" @change="updateSelectedElement" />
              </div>
              <div v-if="selectedElement.type === 'text'" class="property-item">
                <label>文本内容:</label>
                <el-input v-model="selectedElement.content" type="textarea" @change="updateSelectedElement" />
              </div>
            </div>
            <div v-else class="no-selection">
              <p>请选择一个元素进行编辑</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部状态栏 -->
      <div class="sv-status-bar">
        <div class="status-left">
          <span>模板: {{ currentTemplateName }}</span>
        </div>
        <div class="status-center">
          <span v-if="selectedElement">{{ selectedElement.type }} - 选中</span>
          <span v-else>就绪</span>
        </div>
        <div class="status-right">
          <span>显示网格: </span>
          <el-switch v-model="showGrid" @change="toggleGrid" />
        </div>
      </div>
    </el-dialog>
    
    <!-- 打印预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="打印预览"
      width="80%"
      :before-close="handlePreviewClose"
    >
      <div style="min-height: 400px;" id="print-preview-content">
        <!-- 预览内容 -->
        <div 
          v-for="(panel, panelIndex) in templateData.panels" 
          :key="panelIndex"
          style="margin-bottom: 20px;"
        >
          <h3>{{ panel.name }}</h3>
          <div 
            v-for="(item, itemIndex) in panel.items" 
            :key="itemIndex"
            style="margin: 10px 0;"
          >
            <div v-html="renderItem(item)"></div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPrint">确定打印</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 打印设置对话框 -->
    <el-dialog
      v-model="settingsVisible"
      title="打印设置"
      width="600px"
      :before-close="handleSettingsClose"
    >
      <div class="settings-content">
        <el-form label-width="120px">
          <el-form-item label="纸张大小:">
            <el-select v-model="paperSize" style="width: 100%;">
              <el-option label="A4" value="A4"></el-option>
              <el-option label="A3" value="A3"></el-option>
              <el-option label="B5" value="B5"></el-option>
              <el-option label="Letter" value="Letter"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="纸张方向:">
            <el-radio-group v-model="orientation">
              <el-radio label="portrait">纵向</el-radio>
              <el-radio label="landscape">横向</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="页边距:">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-input-number v-model="margins.top" placeholder="上" :min="0"></el-input-number>
              </el-col>
              <el-col :span="6">
                <el-input-number v-model="margins.right" placeholder="右" :min="0"></el-input-number>
              </el-col>
              <el-col :span="6">
                <el-input-number v-model="margins.bottom" placeholder="下" :min="0"></el-input-number>
              </el-col>
              <el-col :span="6">
                <el-input-number v-model="margins.left" placeholder="左" :min="0"></el-input-number>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settingsVisible = false">取消</el-button>
          <el-button type="primary" @click="savePrintSettings">保存设置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入sv-print设计器组件
import { Designer } from '@sv-print/vue3'
// import '@sv-print/vue3/dist/style.css'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
})

// 定义事件发射
const emit = defineEmits(['update:modelValue', 'templateSaved', 'printed'])

// 添加调试日志
console.log('PrintTemplateDesigner component created')
console.log('Props:', props)

// 响应式数据
const visible:any = ref(false)
const previewVisible:any = ref(false)
const settingsVisible:any = ref(false)
const designerRef:any = ref<HTMLElement | null>(null)
const previewRef = ref<HTMLElement | null>(null)
const templateData:any = ref({})
const templateChanged:any = ref(false)
const selectedElement:any = ref(null)
const zoomLevel:any = ref(100)
const showGrid:any = ref(true)
const currentTemplateName:any = ref('未命名模板')
const paperSize:any = ref('A4')
const orientation:any = ref('portrait')
const margins = ref({
  top: 10,
  right: 10,
  bottom: 10,
  left: 10
})

// 定义providers和providerMap
const providers = ref([
  {
    name: '文本',
    type: 'text',
    icon: 'text',
    data: { text: '文本' }
  },
  {
    name: '表格',
    type: 'table',
    icon: 'table',
    data: { 
      columns: [
        { title: '项目', field: 'item' },
        { title: '数值', field: 'value' }
      ],
      data: []
    }
  },
  {
    name: '图片',
    type: 'image',
    icon: 'image',
    data: { url: '' }
  },
  {
    name: '标题',
    type: 'header',
    icon: 'header',
    data: { text: '标题', fontSize: 18, fontWeight: 'bold' }
  },
  {
    name: '段落',
    type: 'paragraph',
    icon: 'paragraph',
    data: { text: '段落内容' }
  }
])

const providerMap:any = ref({
  text: (data:any) => {
    return `<div style="font-size: 14px;">${data.text || ''}</div>`
  },
  table: (data:any) => {
    const columns = data.columns || []
    const tableData = data.data || []
    
    let html = '<table style="width: 100%; border-collapse: collapse; border: 1px solid #ccc;">'
    
    // 表头
    html += '<thead><tr>'
    columns.forEach((col: { title: any }) => {
      html += `<th style="border: 1px solid #ccc; padding: 8px; background-color: #f5f5f5;">${col.title || ''}</th>`
    })
    html += '</tr></thead>'
    
    // 表体
    html += '<tbody>'
    tableData.forEach((row: { [x: string]: any }) => {
      html += '<tr>'
      columns.forEach((col: { field: string | number }) => {
        html += `<td style="border: 1px solid #ccc; padding: 8px;">${row[col.field] || ''}</td>`
      })
      html += '</tr>'
    })
    html += '</tbody></table>'
    
    return html
  },
  image: (data: { url: any }) => {
    return `<img src="${data.url || ''}" style="max-width: 100%;" />`
  },
  header: (data: { fontSize: number; fontWeight: string; text: any }) => {
    const fontSize = data.fontSize || 18
    const fontWeight = data.fontWeight || 'bold'
    return `<div style="font-size: ${fontSize}px; font-weight: ${fontWeight}; text-align: center; margin: 10px 0;">${data.text || ''}</div>`
  },
  paragraph: (data: { text: any }) => {
    return `<div style="font-size: 14px; line-height: 1.5; margin: 10px 0;">${data.text || ''}</div>`
  }
})

// 监听modelValue变化
onMounted(() => {
  console.log('PrintTemplateDesigner mounted, props.modelValue:', props.modelValue)
  visible.value = props.modelValue
  console.log('Visible value set to:', visible.value)
  // 初始化模板数据
  initTemplateData()
})

// 监听props.modelValue的变化
watch(() => props.modelValue, (newValue) => {
  console.log('modelValue changed to:', newValue)
  visible.value = newValue
  console.log('Visible value updated to:', visible.value)
})

// 监听visible变化并更新modelValue
watch(visible, (newValue) => {
  console.log('Visible changed to:', newValue)
  emit('update:modelValue', newValue)
  console.log('Emitted update:modelValue with:', newValue)
})

// 初始化模板数据
const initTemplateData = () => {
  if (props.reportData && props.reportData.patientInfo) {
    // 根据报告数据初始化模板
    templateData.value = {
      panels: [
        {
          name: '报告头部',
          items: [
            {
              type: 'header',
              data: { text: '综合健康报告', fontSize: 24, fontWeight: 'bold' }
            },
            {
              type: 'text',
              data: { text: `报告日期: ${props.reportData.reportDate}` }
            }
          ]
        },
        {
          name: '患者信息',
          items: [
            {
              type: 'text',
              data: { text: `患者姓名: ${props.reportData.patientInfo.name}` }
            },
            {
              type: 'text',
              data: { text: `年龄: ${props.reportData.patientInfo.age}` }
            },
            {
              type: 'text',
              data: { text: `性别: ${props.reportData.patientInfo.gender}` }
            },
            {
              type: 'text',
              data: { text: `身份证号: ${props.reportData.patientInfo.patientId}` }
            },
            {
              type: 'text',
              data: { text: `身高: ${props.reportData.patientInfo.height}` }
            },
            {
              type: 'text',
              data: { text: `体重: ${props.reportData.patientInfo.weight}` }
            }
          ]
        },
        {
          name: '血压信息',
          items: [
            {
              type: 'text',
              data: { text: `收缩压: ${props.reportData.bloodPressure.systolic} mmHg` }
            },
            {
              type: 'text',
              data: { text: `舒张压: ${props.reportData.bloodPressure.diastolic} mmHg` }
            },
            {
              type: 'text',
              data: { text: `评估结果: ${props.reportData.bloodPressure.evaluation}` }
            }
          ]
        },
        {
          name: '血糖信息',
          items: [
            {
              type: 'text',
              data: { text: `空腹血糖: ${props.reportData.bloodGlucose.fasting} mmol/L` }
            },
            {
              type: 'text',
              data: { text: `餐后2小时血糖: ${props.reportData.bloodGlucose.twoHoursAfterMeal} mmol/L` }
            },
            {
              type: 'text',
              data: { text: `糖化血红蛋白: ${props.reportData.bloodGlucose.glycatedHemoglobin} %` }
            }
          ]
        }
      ]
    }
  }
}

// 关闭设计器
const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}

// 关闭设计器
const closeDesigner = () => {
  handleClose()
}

// 处理预览关闭
const handlePreviewClose = () => {
  previewVisible.value = false
}

// 处理设置关闭
const handleSettingsClose = () => {
  settingsVisible.value = false
}

// 新增模板
const newTemplate = () => {
  if (templateChanged.value) {
    ElMessageBox.confirm(
      '当前模板未保存，是否放弃更改？',
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      initTemplateData()
      currentTemplateName.value = '未命名模板'
      templateChanged.value = false
      ElMessage.success('已创建新模板')
    }).catch(() => {
      // 取消操作
    })
  } else {
    initTemplateData()
    currentTemplateName.value = '未命名模板'
  }
}

// 打开模板
const openTemplate = () => {
  // 这里应该实现模板选择和加载逻辑
  ElMessage.info('模板选择功能开发中')
}

// 导出模板
const exportTemplate = () => {
  if (!templateData.value.panels || templateData.value.panels.length === 0) {
    ElMessage.warning('没有可导出的模板')
    return
  }
  
  // 创建下载链接
  const dataStr = JSON.stringify(templateData.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `${currentTemplateName.value}.json`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
  
  ElMessage.success('模板导出成功')
}

// 导入模板
const importTemplate = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const importedData = JSON.parse(e.target?.result as string)
          templateData.value = importedData
          templateChanged.value = true
          currentTemplateName.value = file.name.replace('.json', '')
          ElMessage.success('模板导入成功')
        } catch (error) {
          ElMessage.error('模板文件格式错误')
        }
      }
      reader.readAsText(file)
    }
  }
  input.click()
}

// 撤销操作
const undo = () => {
  ElMessage.info('撤销功能开发中')
}

// 重做操作
const redo = () => {
  ElMessage.info('重做功能开发中')
}

// 删除选中元素
const deleteSelected = () => {
  if (selectedElement.value) {
    ElMessageBox.confirm(
      '确定要删除选中的元素吗？',
      '确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      // 这里应该实现实际的删除逻辑
      selectedElement.value = null
      templateChanged.value = true
      ElMessage.success('元素已删除')
    }).catch(() => {
      // 取消操作
    })
  } else {
    ElMessage.warning('请先选择要删除的元素')
  }
}

// 放大
const zoomIn = () => {
  if (zoomLevel.value < 200) {
    zoomLevel.value += 10
  }
}

// 缩小
const zoomOut = () => {
  if (zoomLevel.value > 50) {
    zoomLevel.value -= 10
  }
}

// 适应页面
const fitToPage = () => {
  zoomLevel.value = 100
}

// 缩放变化
const onZoomChange = () => {
  // 缩放变化时的处理
}

// 打印设置
const printSettings = () => {
  settingsVisible.value = true
}

// 保存打印设置
const savePrintSettings = () => {
  // 保存打印设置
  settingsVisible.value = false
  ElMessage.success('打印设置已保存')
}

// 切换网格显示
const toggleGrid = () => {
  // 切换网格显示状态
}

// 添加文本组件
const addTextComponent = () => {
  addComponent('text', { text: '新文本' })
}

// 添加图片组件
const addImageComponent = () => {
  addComponent('image', { url: '' })
}

// 添加表格组件
const addTableComponent = () => {
  addComponent('table', { 
    columns: [
      { title: '项目', field: 'item' },
      { title: '数值', field: 'value' }
    ],
    data: []
  })
}

// 添加线条组件
const addLineComponent = () => {
  addComponent('line', { style: { stroke: '#000', strokeWidth: 1 } })
}

// 添加矩形组件
const addRectangleComponent = () => {
  addComponent('rectangle', { style: { fill: '#f0f0f0', stroke: '#000', strokeWidth: 1 } })
}

// 添加患者信息组件
const addPatientInfo = () => {
  if (props.reportData && props.reportData.patientInfo) {
    addComponent('text', { text: `患者: ${props.reportData.patientInfo.name}` })
  }
}

// 添加血压信息组件
const addBloodPressure = () => {
  if (props.reportData && props.reportData.bloodPressure) {
    addComponent('text', { 
      text: `血压: ${props.reportData.bloodPressure.systolic}/${props.reportData.bloodPressure.diastolic} mmHg` 
    })
  }
}

// 添加血糖信息组件
const addBloodGlucose = () => {
  if (props.reportData && props.reportData.bloodGlucose) {
    addComponent('text', { 
      text: `空腹血糖: ${props.reportData.bloodGlucose.fasting} mmol/L` 
    })
  }
}

// 添加图表组件
const addChart = () => {
  addComponent('chart', { type: 'line', data: [] })
}

// 添加组件通用方法
const addComponent = (type: string, data: { text?: string; url?: string; columns?: { title: string; field: string }[]; data?: never[]; style?: { stroke: string; strokeWidth: number } | { fill: string; stroke: string; strokeWidth: number }; type?: string }) => {
  if (!templateData.value.panels) {
    templateData.value.panels = [{ name: '默认面板', items: [] }]
  }
  
  const newItem = {
    type: type,
    data: data,
    id: Date.now().toString(),
    x: 100,
    y: 100,
    width: 200,
    height: 50
  }
  
  templateData.value.panels[0].items.push(newItem)
  selectedElement.value = newItem
  templateChanged.value = true
  ElMessage.success(`已添加${getComponentName(type)}组件`)
}

// 获取组件名称
const getComponentName = (type: string | number) => {
  const names = {
    'text': '文本',
    'image': '图片',
    'table': '表格',
    'line': '线条',
    'rectangle': '矩形',
    'chart': '图表'
  }
  return names[type as keyof typeof names] || type
}

// 更新选中元素
const updateSelectedElement = () => {
  templateChanged.value = true
}

// 处理模板设计完成事件
const handleDesigned = (data: any) => {
  templateData.value = data
  templateChanged.value = true
}

// 处理模板变化事件
const handleTemplateChange = (data: any) => {
  templateData.value = data
  templateChanged.value = true
}

// 渲染单个项目
const renderItem = (item: { type: string | number; data: any }) => {
  if (providerMap.value[item.type]) {
    return providerMap.value[item.type](item.data)
  }
  return ''
}

// 预览打印
const previewPrint = () => {
  // 实现真实的打印预览功能
  previewVisible.value = true
}

// 保存模板
const saveTemplate = () => {
  ElMessage.success('模板保存成功')
  templateChanged.value = false
  emit('templateSaved', templateData.value)
}

// 直接打印
const printDirectly = () => {
  // 创建一个隐藏的iframe用于打印
  const iframe:any = document.createElement('iframe')
  iframe.style.position = 'absolute'
  iframe.style.top = '-1000px'
  iframe.style.left = '-1000px'
  document.body.appendChild(iframe)
  
  // 检查iframe.contentWindow是否可用，防止为null
  const iframeWin = iframe.contentWindow
  if (!iframeWin) {
    ElMessage.error('无法生成打印窗口，请稍后再试')
    document.body.removeChild(iframe)
    return
  }
  const iframeDoc = iframeWin.document
  iframeDoc.open()
  
  // 构建打印内容
  let printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>健康报告打印</title>
      <style>
        body { font-family: Arial, sans-serif; }
        .panel { margin-bottom: 20px; }
        .panel h3 { margin: 10px 0; }
        .item { margin: 10px 0; }
        table { width: 100%; border-collapse: collapse; border: 1px solid #ccc; }
        th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background-color: #f5f5f5; }
        img { max-width: 100%; }
      </style>
    </head>
    <body>
  `
  
  // 添加模板内容
  templateData.value.panels.forEach((panel: { name: any; items: any[] }) => {
    printContent += `<div class="panel"><h3>${panel.name}</h3>`
    panel.items.forEach((item: any) => {
      printContent += `<div class="item">${renderItem(item)}</div>`
    })
    printContent += `</div>`
  })
  
  printContent += `
    </body>
    </html>
  `
  
  iframeDoc.write(printContent)
  iframeDoc.close()
  
  // 等待内容加载完成后打印
  iframe.onload = () => {
    iframe.contentWindow.focus()
    iframe.contentWindow.print()
    document.body.removeChild(iframe)
  }
  
  // 如果onload没有触发，则延迟执行
  setTimeout(() => {
    if (iframe.parentNode) {
      iframe.contentWindow.focus()
      iframe.contentWindow.print()
      document.body.removeChild(iframe)
    }
  }, 1000)
  
  ElMessage.success('正在打印...')
  emit('printed')
}

// 确认打印
const confirmPrint = () => {
  previewVisible.value = false
  ElMessage.success('打印成功')
  emit('printed')
}

// 格式化当前日期
const formatCurrentDate = () => {
  const date = new Date()
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
</script>

<style scoped>
.print-template-designer {
  width: 100%;
  height: 100%;
}

.sv-print-dialog .el-dialog__body {
  padding: 0;
  margin: 0;
  height: calc(100% - 40px);
  display: flex;
  flex-direction: column;
}

/* 顶部工具栏 */
.sv-top-toolbar {
  background-color: #7928ca;
  color: white;
  padding: 4px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #5c21a6;
}

.toolbar-section {
  display: flex;
  align-items: center;
  margin: 0 5px;
}

.toolbar-section .el-button-group .el-button {
  background-color: #7928ca;
  border-color: #7928ca;
  color: white;
}

.toolbar-section .el-button-group .el-button:hover {
  background-color: #5c21a6;
  border-color: #5c21a6;
}

.toolbar-section .el-input-number {
  width: 80px;
  background-color: white;
  margin: 0 5px;
}

.toolbar-section .el-input-number .el-input__inner {
  color: black;
}

/* 主容器 */
.sv-main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
  background-color: #f0f0f0;
}

/* 左侧面板 */
.sv-left-panel {
  width: 200px;
  background-color: white;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 10px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  font-weight: bold;
}

.panel-content {
  flex: 1;
  overflow-y: auto;
}

.component-category {
  margin-bottom: 15px;
}

.category-title {
  padding: 8px 10px;
  font-weight: bold;
  background-color: #f9f9f9;
  border-bottom: 1px solid #e0e0e0;
}

.component-list {
  padding: 5px;
}

.component-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 2px 0;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.component-item:hover {
  background-color: #f0f0f0;
}

.component-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 中间画布 */
.sv-center-canvas {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
  background-color: #f0f0f0;
  position: relative;
}

.canvas-header {
  padding: 5px 10px;
  background-color: #e0e0e0;
  border-bottom: 1px solid #d0d0d0;
}

.page-info {
  display: flex;
  gap: 20px;
}

.canvas-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 20px;
  transform-origin: top left;
  transition: transform 0.3s ease;
}

.designer-area {
    background-color: white;
    border: 1px solid #d0d0d0;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 794px;
    min-height: 1123px;
    position: relative;
    padding: 20px;
    overflow-y: auto;
  }
  
  /* 健康报告样式 */
  .health-report-content {
    font-family: Arial, sans-serif;
    color: #333;
    line-height: 1.6;
  }
  
  .report-header {
    text-align: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #409EFF;
  }
  
  .report-title {
    font-size: 24px;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 10px;
  }
  
  .report-date {
    color: #666;
    font-size: 14px;
  }
  
  .report-section {
    margin-bottom: 30px;
  }
  
  .section-title {
    font-size: 18px;
    color: #409EFF;
    margin-bottom: 15px;
    padding-left: 10px;
    border-left: 4px solid #409EFF;
  }
  
  .patient-info {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
  }
  
  .info-item {
    display: flex;
    align-items: center;
  }
  
  .info-label {
    font-weight: bold;
    color: #666;
    margin-right: 10px;
    min-width: 70px;
  }
  
  .info-value {
    color: #333;
  }
  
  .blood-pressure-chart {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
  
  .pressure-info {
    flex: 1;
    text-align: center;
  }
  
  .pressure-main {
    font-size: 24px;
    font-weight: bold;
  }
  
  .pressure-value.systolic {
    color: #ff4d4f;
  }
  
  .pressure-value.diastolic {
    color: #1890ff;
  }
  
  .pressure-unit {
    font-size: 16px;
    color: #666;
    margin: 0 5px;
  }
  
  .pressure-separator {
    margin: 0 10px;
  }
  
  .pressure-evaluation {
    margin-top: 10px;
    color: #666;
  }
  
  .pressure-time {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
  }
  
  .chart-container {
    flex: 2;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .blood-pressure-bar {
    display: flex;
    align-items: flex-end;
    gap: 20px;
    margin-right: 20px;
  }
  
  .bar-item {
    width: 40px;
  }
  
  .bar-item.danger {
    background-color: #ff4d4f;
  }
  
  .bar-item.warning {
    background-color: #faad14;
  }
  
  .bar-item.normal {
    background-color: #52c41a;
  }
  
  .bar-item.low {
    background-color: #1890ff;
  }
  
  .chart-labels {
    display: flex;
    flex-direction: column;
    gap: 8px;
    font-size: 12px;
    color: #666;
  }
  
  .indicator-score {
    display: flex;
    justify-content: space-around;
    background-color: #f8f8f8;
    padding: 15px;
    border-radius: 5px;
  }
  
  .score-item {
    text-align: center;
  }
  
  .score-item span:first-child {
    display: block;
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  
  .score-number {
    font-size: 20px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .glucose-info {
    margin-bottom: 20px;
  }
  
  .glucose-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  
  .glucose-label {
    color: #666;
  }
  
  .glucose-value {
    font-weight: bold;
    color: #333;
  }
  
  .glucose-evaluation {
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
  
  .evaluation-label {
    color: #666;
    margin-right: 10px;
  }
  
  .evaluation-value {
    font-weight: bold;
    color: #409EFF;
  }
  
  .glucose-time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }
  
  .glucose-chart {
    margin-bottom: 20px;
  }
  
  .chart-row {
    display: flex;
    height: 40px;
    margin-bottom: 10px;
  }
  
  .chart-bar {
    height: 100%;
  }
  
  .chart-bar.low {
    background-color: #1890ff;
  }
  
  .chart-bar.normal {
    background-color: #52c41a;
  }
  
  .chart-bar.high {
    background-color: #ff4d4f;
  }
  
  .chart-legend {
    display: flex;
    justify-content: space-around;
    font-size: 12px;
    color: #666;
  }
  
  /* 表格样式 */
  table {
    width: 100%;
    border-collapse: collapse;
  }
  
  th, td {
    border: 1px solid #e0e0e0;
    padding: 10px;
    text-align: center;
  }
  
  th {
    background-color: #f8f8f8;
    font-weight: bold;
    color: #666;
  }
  
  .biochemical-table,
  .medication-table {
    overflow-x: auto;
  }
  
  .exercise-info {
    background-color: #f8f8f8;
    padding: 15px;
    border-radius: 5px;
  }
  
  .exercise-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
  }
  
  .stat-item {
    text-align: center;
  }
  
  .stat-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
  }
  
  .stat-value {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .overall-score {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .score-display {
    text-align: center;
  }
  
  .score-number-large {
    font-size: 48px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .score-level {
    font-size: 18px;
    color: #666;
    margin-top: 5px;
  }
  
  .score-breakdown {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

.canvas-footer {
  height: 1px;
}

.ruler-horizontal {
  height: 1px;
  background-color: #d0d0d0;
}

/* 右侧属性面板 */
.sv-right-panel {
  width: 240px;
  background-color: white;
  border-left: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.property-section {
  padding: 10px;
}

.property-title {
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e0e0e0;
}

.property-item {
  margin-bottom: 10px;
}

.property-item label {
  display: block;
  margin-bottom: 5px;
  font-size: 12px;
}

.property-item .el-input-number {
  width: 100%;
}

.property-item .el-input {
  width: 100%;
}

.no-selection {
  padding: 20px;
  text-align: center;
  color: #999;
}

/* 底部状态栏 */
.sv-status-bar {
  background-color: #f5f5f5;
  border-top: 1px solid #e0e0e0;
  padding: 4px 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.status-left, .status-center, .status-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-right .el-switch {
  margin-left: 5px;
}

/* 设置对话框样式 */
.settings-content {
  padding: 20px 0;
}

.settings-content .el-form-item {
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .sv-left-panel {
    width: 180px;
  }
  .sv-right-panel {
    width: 220px;
  }
}
</style>